package com.example.demoexample.communication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.ImageView;

import com.example.demoexample.R;
import com.example.demoexample.ui.base.BaseActivity;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DownloadImgActivity extends BaseActivity {

    @BindView(R.id.btn_download)
    Button btnDownload;
    @BindView(R.id.iv_bg)
    ImageView ivBg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_img);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_download)
    public void onViewClicked() {
        new Thread(new MyTherad()).start();
        showProgressDialog();
    }

    private Handler handler = new Handler() {
        // 在Handler中获取消息，重写handleMessage()方法
        @Override
        public void handleMessage(Message msg) {
            // 判断消息码是否为0
            if (msg.what == 0) {
                byte[] data = (byte[]) msg.obj;
                Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                ivBg.setImageBitmap(bmp);

            }
            dismissProgressDialog();
        }
    };

    public class MyTherad implements Runnable {

        @Override
        public void run() {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://pic31.nipic.com/20130804/7487939_090818211000_2.jpg");
            HttpResponse httpResponse = null;
            try {
                httpResponse = defaultHttpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity());
                    Message message = Message.obtain();
                    message.obj = bytes;
                    message.what = 0;
                    handler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
                dismissProgressDialog();
            }

        }
    }

}
